import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  Animated,
  TextInput,
  TouchableOpacity,
  Platform,
  Dimensions,
  Keyboard
} from 'react-native';
import styles from './myMoneyStyle';
import SimpleDialog from '../global/SimpleViewDialog';
import api from '../../services/api';
import ToastTip from '../global/ToastTip';
import LoadingTip from '../global/LoadingTip';
import Touch from '../global/Touch';
import PasswordInput from '../global/PasswordInput';

const Wheight = Dimensions.get('window').height;
const Wwidth = Dimensions.get('window').width;
const percent = 0.078125; // 弹窗左右间距百分比
let margin = Wwidth * percent; // 弹窗左右间距
let pwdWidth = Wwidth * (1 - percent * 2) * percent * 10; // 密码框长度
let padding = (Wwidth - 2 * margin - pwdWidth) / 2; // 关闭icon的右间距padding

let windowHeight = 111;
class MyMoney extends Component {
    constructor(props) {
		super(props);

		this.state = {
            scrollY: new Animated.Value(0),
            pay_count:'',
            isBindCard: false,
            cardInfo:null,
            balance: 0.00, //算过的余额
            feeCount: 0.00, //提现手续费用
            disable: false,
            isPwdDialogVisible: false, // 是否显示提现密码弹窗
            isPwdSetDialogVisible: false, // 是否显示提现密码设置弹窗
            errorText: '', // 错误信息
            shopInfo:{
                incomeCycle:0,
            },
            shopAllBalance:0.00,
            shopWithdrawBalance:0.00,
		};

		// this._getTabHeight = this._getTabHeight.bind(this);
		// this._onChangeTab = this._onChangeTab.bind(this);

		this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    async _onNavigatorEvent(event){
        console.log("##$$$$$$$$$$", event);

        if (event.id === 'didAppear') { // 出现时
            // this._onRefresh();
            // 关闭弹窗
            let res = await api.post("/card/mycard",{});
            if(res.data){//已绑卡
                this.setState({
                    isBindCard:true,
                    cardInfo:res.data,
                    isPwdDialogVisible: false,
                    isPwdSetDialogVisible: false,
                    pay_count:'',
                    open:false,
                });
            } else {
                this.setState({
                    isPwdDialogVisible: false,
                    isPwdSetDialogVisible: false,
                    pay_count:'',
                    open:false,
                });
            }

		}
    }

    componentWillMount(){
        // this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
        // this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
    }


    _keyboardDidShow(){


    }

    _keyboardDidHide(){

    }

    componentDidMount() {
        // this._hasFirstWithdraw();
        let {session} = this.props;
        if (session.user.isShop) {
            this._getShopBalanceCount();
            this._getShopsDetailInfo();
        }else{
            this._getBalanceCount();
        }
        
	}

    componentWillReceiveProps(nextProps) {
    }

    componentWillUnmount(){
        // this.keyboardDidShowListener.remove();
        // this.keyboardDidHideListener.remove();
    }

    async _hasFirstWithdraw(card_no){
        let res = await api.post("/card/hasfirstwithdraw",{card_no});
        if(res){//
            this.setState({
                feeCount: res.data
            });
        }
    }

    async _getBalanceCount(){
        let {order_reward, order_obj_price} = this.props;
        let sumres = await api.post("/card/withdrawcount",{});
        //余额加上了商品金额
        if(sumres){
            this.setState({
                balance:(order_reward+order_obj_price-sumres.data)
            });
        }
    }

    async _getShopBalanceCount(){
        let shopSumres = await api.post("/housekeeper/shopsKeeperBalance",{});
        if (shopSumres.cd != 0) {

            this.refs.toast.show(shopSumres.msg);
            return;
        }

        this.setState({
            shopAllBalance:shopSumres.data.allBalance,
            shopWithdrawBalance:shopSumres.data.withdrawBalance,
        })
    }

    async _getShopsDetailInfo(){
        let {session} = this.props;
        let shopDetailResult = await api.post('/privilege/shops/detailByKeeperId',{keeperId:session.user.id});
        if (shopDetailResult.cd != 0) {

            this.refs.toast.show(shopSumres.msg);
            return;
        }
        this.setState({
            shopInfo:shopDetailResult.data,
        })
    }

    getScrollResponder() {
      return this._scrollView.getScrollResponder();
    }

    setNativeProps(props) {
      this._scrollView.setNativeProps(props);
    }

    _addUser(){

    }

    _actionWithdraw(){
        let {navigator,session} = this.props;
        let {isBindCard, cardInfo} = this.state;
        if(isBindCard){
            this._hasFirstWithdraw(cardInfo.bankCardNo);
            this.setState({open: true});
        } else if (session.user && session.user.withdraw_password == null) {
            this.setState({isPwdSetDialogVisible:true});
        } else {
            navigator.push({
                title: "添加银行卡",
                backButtonTitle:'',
    			screen: 'housekeeperapp.hkbindcard',
    			passProps: {
    				// orderId
    			},
                navigatorStyle:{
                    navBarHidden: false,
                    tabBarHidden: true,
                    navBarTextColor: 'white',
                	navBarButtonColor: 'white',
                	navBarBackgroundColor: '#EA5404',
                    statusBarColor: '#EA5404',
                    navBarTitleTextCentered: true,
                    topBarElevationShadowEnabled:false
                },
                navigatorButtons: {
                    leftButtons:[
                        {
                            id: 'back',
                            icon: require("../../../img/hk_back_icon.png")
                        }
                    ]
                }
    			// backButtonHidden: true,
    		});
        }

    }

    _showWithdrawInfo(){
        let {navigator} = this.props;
        navigator.push({
            title: "交易明细",
            backButtonTitle:'',
			screen: 'housekeeperapp.withdrawlist',
			passProps: {
				// orderId
			},
            navigatorStyle:{
                navBarHidden: false,
                tabBarHidden: true,
                navBarTextColor: 'white',
            	navBarButtonColor: 'white',
            	navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true,
                topBarElevationShadowEnabled:false
            },
            navigatorButtons: {
                leftButtons:[
                    {
                        id: 'back',
                        icon: require("../../../img/hk_back_icon.png")
                    }
                ]
            }
			// backButtonHidden: true,
		});
    }

    _validateAmount() {
        let {session} = this.props;
        let {pay_count, balance,feeCount} = this.state;
        if(!pay_count){
            this.refs.toast.show('请输入提现金额');
            return false;
        }
        if (pay_count == 0) {
            this.refs.toast.show('提现金额需大于0');
            return false;
        }
        if (session.user.isShop == 1) {
            if (pay_count <= feeCount) {
                this.refs.toast.show('提现金额需大于提现手续费');
                return false;
            }
            return true;
        }
        if(pay_count < 20){
            this.refs.toast.show('20元起提');
            return false;
        }

        return true;
        
        
    }

    async _showPwdSetDialog(){
        if (this._validateAmount()) {
            this.setState({isPwdSetDialogVisible:true,open:false});
        }
    }

    async _showPwdDialog(){
        if (this._validateAmount()) {
            this.setState({isPwdDialogVisible:true,open:false});
        }
    }

    async _payAction(password) {

        let {loadingShow,pay_count,feeCount} = this.state;
        if(loadingShow){//正在加载中
            return;
        }

        if (password.length != 6) {
            return;
        }

        this.setState({loadingShow: true});

        // 首先需要确认提现密码
        let res = await api.post("/housekeeper/validateWithdrawPwd",{pwd:password});
        if (res.cd == 0) {
            Keyboard.dismiss();
            let data = await api.post("/card/pay",{pay_count, true_count: (pay_count - feeCount).toFixed(2)});

            if(data && data.data=='交易成功'){
                this.refs.toast.show('提现成功', 1500, () =>{
                    
                    this.setState({open:false,loadingShow:false,pay_count:''});
                    this._getBalanceCount();
                    this.props.navigator.pop();
                });
            }else{
                this.setState({loadingShow:false});
                data && this.refs.toast.show(data.data, 2000);
            }
        } else {
            this.setState({errorText:'密码错误，请重试',loadingShow:false});
        }
    }
    _closeAction(){
        this.setState({open:false, isPwdDialogVisible: false,isPwdSetDialogVisible: false, pay_count:'', disable:false});
    }

    _goSettingWithdrawPwd() {
        let {navigator} = this.props;
        navigator.push({
            title: "修改提现密码",
            backButtonTitle:'',
            screen: 'housekeeperapp.settingwithdrawpassword',
            passProps: {
                // orderId
            },
            navigatorStyle:{
                navBarHidden: false,
                tabBarHidden: true,
                navBarTextColor: 'white',
                navBarButtonColor: 'white',
                navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true,
                topBarElevationShadowEnabled:false
            },
        })
    }

    // 更换银行卡界面
    _goChangeCard() {
        let {navigator,session} = this.props;
        let {cardInfo} = this.state;
        if (session && session.user && session.user.withdraw_password) {
            this.props.navigator.push({
                title: "我的银行卡",
                backButtonTitle:'',
                screen: 'housekeeperapp.cardIndex',
                passProps: {
                    showChangeDialog: true
                },
                navigatorStyle:{
                    navBarHidden: false,
                    tabBarHidden: true,
                    navBarTextColor: 'white',
                    navBarButtonColor: 'white',
                    navBarBackgroundColor: '#EA5404',
                    statusBarColor: '#EA5404',
                    navBarTitleTextCentered: true,
                    topBarElevationShadowEnabled:false
                },
            });
        } else {
            navigator.push({
                title: "更换银行卡",
                backButtonTitle:'',
                screen: 'housekeeperapp.hkbindcard',
                passProps: {
                    type: 'CHANGE_CARD',
                    old_id:cardInfo.id
                },
                navigatorStyle:{
                    navBarHidden: false,
                    tabBarHidden: true,
                    navBarTextColor: 'white',
                    navBarButtonColor: 'white',
                    navBarBackgroundColor: '#EA5404',
                    statusBarColor: '#EA5404',
                    navBarTitleTextCentered: true,
                    topBarElevationShadowEnabled:false
                }
            })
        }
    }

    _renderPwdDialog() {
        let {pay_count,feeCount,errorText} = this.state;
        let fee = feeCount;
        if (pay_count == '') {
            return null;
        }
        return (
            <SimpleDialog
                offset={this.state.offset}
                open={this.state.isPwdDialogVisible}
                closeOnTouchOutside={false}
                modalStyle={{padding:0,margin,overflow:'hidden'}}
                modalDidOpen={() => console.log('modal did open')}
                style={{alignItems: 'center'}}>
                    <View style={[styles.dialogContainer,{height:250}]}>
                        <View style={styles.dialogTitle}>
                            <Text style={styles.dialogTitleText}>
                                请输入提现密码
                            </Text>
                        </View>
                        <TouchableOpacity onPress={this._closeAction.bind(this)} style={styles.closeIcon}>
                            <Image source={require('../../../img/dialog_close.png')}/>
                        </TouchableOpacity>

                        <View style={{marginTop:10,alignItems:'center'}}>
                            <Text style={styles.payText}>提现金额</Text>
                            <View>
                                <Text style={{fontSize:32,color:'#565656'}}>¥{(pay_count ? (pay_count - 0) : 0).toFixed(2)}</Text>
                            </View>
                            <View>
                                <Text style={styles.feeText}>提现手续费：<Text style={{color:'#EA5404'}}>{fee+'元'}</Text>，实际到账：<Text style={{color:'#EA5404'}}>{this.state.pay_count-fee<0?0:(this.state.pay_count-fee).toFixed(2)}元</Text></Text>
                            </View>
                        </View>
                        <View style={{alignItems:'center',marginTop:-10}}>
                            <PasswordInput hiddeCursor={true} ref="pwdinput" callbackFn={this._payAction.bind(this)} type="DO_WITHDRAW" errorText={errorText} width={pwdWidth}/>
                            <View style={{flexDirection:'column',width:pwdWidth,alignItems:'flex-end'}}>
                                <TouchableOpacity  onPress={this._goSettingWithdrawPwd.bind(this)}>
                                    <Text style={{fontSize:14,color:'#5DBAFD'}}>忘记密码</Text>
                                </TouchableOpacity>
                            </View>
                        </View>

                    </View>
              </SimpleDialog>
        )
    }
    // 设置提现密码请求
    async _setWithdrawPwdAction(password){
        password = password || this.refs.pwdinput.state.password;
        let { isBindCard } = this.state;
        let { session, actions, dispatch, navigator } = this.props;

        // 密码不符合规范
        if (this.refs.pwdinput.password.length == 6) {
            if (password != this.refs.pwdinput.password) {
                this.setState({errorText:'两次输入不一致，请重新输入'});
                return;
            }
        } else {
            this.setState({errorText:'请输入6位数字密码'});
            return;
        }

        let res = await api.post("/housekeeper/setWithdrawPwd",{pwd:password,pwd_confirm:password});

        if(res.cd == 1){
            this.refs.toast.show(res.msg);
            return;
        }

        if (res.data) {
            let state = {isPwdSetDialogVisible:false};
            // 显示输入提现密码框
            if (isBindCard) {
                Object.assign(state,{isPwdDialogVisible:true});
            }
            this.setState({isPwdSetDialogVisible:false,isPwdDialogVisible:true,errorText:''},() =>{
                this.refs.toast.show('设置成功');
                // 更新本地用户状态
                dispatch(actions.session.session_change({
                    ticket:session.stoken,
                    userId:session.user.id,
                    reload: false,
                    group:session.user.group
                }));


                // 对于未绑卡进行不同处理
                if (!isBindCard) {
                    setTimeout(function () {
                        navigator.push({
                            title: "添加银行卡",
                            backButtonTitle:'',
                			screen: 'housekeeperapp.hkbindcard',
                			passProps: {
                				// orderId
                			},
                            navigatorStyle:{
                                navBarHidden: false,
                                tabBarHidden: true,
                                navBarTextColor: 'white',
                            	navBarButtonColor: 'white',
                            	navBarBackgroundColor: '#EA5404',
                                statusBarColor: '#EA5404',
                                navBarTitleTextCentered: true,
                                topBarElevationShadowEnabled:false
                            },
                			// backButtonHidden: true,
                		});
                    }, 1000);
                }
            });
        }
    }

    // 设置提现密码弹窗
    _renderPwdSetDialog() {
        let {errorText} = this.state;
        let disable = false;
        return (
            <SimpleDialog
                offset={this.state.offset}
                open={this.state.isPwdSetDialogVisible}
                closeOnTouchOutside={false}
                modalStyle={{padding:0,margin:15,overflow:'hidden'}}
                modalDidOpen={() => console.log('modal did open')}
                style={{alignItems: 'center'}}>
                    <View style={[styles.dialogContainer,{height:240}]}>
                        <View style={styles.dialogTitle}>
                            <Text style={styles.dialogTitleText}>
                                请设置提现密码
                            </Text>
                        </View>
                        <TouchableOpacity onPress={this._closeAction.bind(this)} style={styles.closeIcon}>
                            <Image source={require('../../../img/dialog_close.png')}/>
                        </TouchableOpacity>
                        <View style={{alignItems:'center',marginTop:20}}>
                            <PasswordInput hiddeCursor={true} ref="pwdinput" type="SET_WITHDRAW_PASSWORD" errorText={errorText} width={pwdWidth}/>
                        </View>
                        <View style={[styles.submitBtnContainer,{marginTop:10,marginLeft:padding,marginRight:padding},disable?{backgroundColor:'#DEDEDE'}:{}]}>
                            <Touch onPress={disable?null:this._setWithdrawPwdAction.bind(this)} style={styles.submitBtn}>
                                <Text style={[styles.submitBtnText,disable?{color:'#f5f5f5'}:{}]}>确定</Text>
                            </Touch>
                        </View>
                    </View>
              </SimpleDialog>
        )
    }
    render() {
        let { scrollY, cardInfo, balance, feeCount, disable } = this.state;
        let { session } = this.props;
        let fee = feeCount;

        return (
            <View style={styles.container}>
                <Animated.View
                    style={[styles.headContainer, {
                        height: windowHeight,
                        transform: [{
                            translateY: scrollY.interpolate({
                                inputRange: [ -windowHeight, 0, windowHeight],
                                outputRange: [windowHeight/2, 0, -windowHeight/3]
                            })
                        },{
                            scale: scrollY.interpolate({
                                inputRange: [ -windowHeight, 0, windowHeight],
                                outputRange: [2, 1, 1]
                            })
                        }]
                    }]}>
                        <Image style={styles.headBg} source={require('../../../img/hk_mymoney_bg.png')}/>
                </Animated.View>

                <ScrollView
                    ref={component => { this._scrollView = component; }}
                    style={styles.scrollContainer}
                    onScroll={Animated.event(
                      [{ nativeEvent: { contentOffset: { y: this.state.scrollY }}}]
                    )}
                    scrollEventThrottle={16}>
                    <Animated.View style={{
                        position: 'relative',
                        alignItems: 'center',
                        backgroundColor: 'transparent',
                        height: windowHeight,
                        opacity: scrollY.interpolate({
                            inputRange: [-windowHeight, 0, windowHeight / 1.2],
                            outputRange: [1, 1, 0]
                        }),
                    }}>
                    </Animated.View>
                    <View style={styles.scrollContent}>
                        <Text style={styles.headText}>我的余额</Text>
                        {
                            session.user.isShop == 1?
                            <Text style={styles.headMoneyText}>¥{this.state.shopAllBalance?this.state.shopAllBalance.toFixed(2):"0.00"}</Text>
                            :
                            <Text style={styles.headMoneyText}>¥{balance.toFixed(2)}</Text>
                        }
                        
                        {
                            session.user.isShop == 1?
                            <View
                                style={{flex:1,flexDirection:'row',justifyContent:'center'}}
                            >
                            <View
                                style={styles.canWithdrawMoney}
                            >
                                <Text style={{color:'#EA5404',fontSize:15}}>
                                    可提现金额：¥{this.state.shopWithdrawBalance?this.state.shopWithdrawBalance.toFixed(2):'0.00'}
                                </Text>
                            </View>
                            </View>
                            :
                            null
                        }
                        <View style={styles.headBtnC}>
                            <Touch onPress={this._actionWithdraw.bind(this)}>
                                <View style={styles.addWithdraw}>
                                    <Image style={styles.addWithdrawImage} source={require('../../../img/hk_mymoney_btn_icon.png')} />
                                    <Text style={styles.addWithdrawBtnText}>
                                        申请提现
                                    </Text>
                                </View>
                            </Touch>
                            <Touch onPress={this._showWithdrawInfo.bind(this)}>
                                <Text style={styles.addWithdrawInfoText}>
                                    查看交易明细>
                                </Text>
                            </Touch>
                        </View>
                        
                    </View>
                </ScrollView>
                {session.user.isShop == 1 && this.state.shopInfo.incomeCycle > 0? 
                        <View 
                            style={styles.shopWithdrawTipsContainer}
                        >
                            <Text>
                                温馨提示：
                            </Text>
                            <Text>
                                账户结算周期为{this.state.shopInfo.incomeCycle}天，发起提现后T+1到账。
                            </Text>
                        </View>
                    :
                    null
                }
                {this._renderPwdDialog()}
                {this._renderPwdSetDialog()}
                <SimpleDialog
                    offset={this.state.offset}
                    open={this.state.open}
                    closeOnTouchOutside={false}
                    modalStyle={{padding:0,margin:15,overflow:'hidden'}}
                    modalDidOpen={() => console.log('modal did open')}
                    style={{alignItems: 'center'}}>
                        <View style={styles.dialogContainer}>
                            <TouchableOpacity onPress={this._closeAction.bind(this)} style={styles.closeIcon}>
                                <Image source={require('../../../img/dialog_close.png')}/>
                            </TouchableOpacity>
                            <View style={styles.formItem}>
                                <View style={[styles.formItemFlex,{flex:3}]}>
                                    <Text style={styles.leftText}>到账银行卡 <Text style={styles.rightText}>{cardInfo&&cardInfo.bankName}（{cardInfo&&cardInfo.bankCardNo.substring(cardInfo.bankCardNo.length-4)}）</Text></Text>
                                </View>
                                <TouchableOpacity onPress={this._goChangeCard.bind(this)} style={[styles.formItemFlex,{alignItems:'flex-end'}]}>
                                    <Text style={{fontSize:14,color:'#5DBAFD'}}>更换</Text>
                                </TouchableOpacity>

                            </View>
                            <View style={{marginTop:15}}>
                                <Text style={styles.payText}>提现金额</Text>
                                <View style={styles.inputContent}>
                                    <Text style={styles.subStyle}>¥</Text>
                                    <TextInput
                                        style={styles.inputStyle}
                                        editable={true}
                                        autoFocus={true}
                                        value={this.state.pay_count + ''}
                                        keyboardType={'numeric'}
                                        clearButtonMode={'while-editing'}
                                        underlineColorAndroid={'#ffffff'}
                                        placeholder={session.user.isShop == 1?
                                            `可提现金额：¥${this.state.shopWithdrawBalance.toFixed(2)}`
                                            :
                                            `20元起提`
                                        }
                                        onFocus={() =>{
                                            if(Platform.OS == 'ios'){
                                                this.setState({offset: -100});
                                            }
                                        }}
                                        onChangeText={(text) =>{
                                            let {pay_count} = this.state;
                                            if(text && !/^\d+(\.\d{0,2})?$/.test(text)){
                                                this.setState({pay_count:pay_count});
                                                return;
                                            }
                                            let {session} = this.props;
                                            if (session.user.isShop == 1) {
                                                let {shopWithdrawBalance} = this.state;
                                                if(shopWithdrawBalance < text){
                                                    if(!disable){
                                                        this.refs.toast.show('输入金额超过账户余额',1000);
                                                        this.setState({disable:true,pay_count:text});
                                                    }
                                                }else{
                                                    this.setState({pay_count:text, disable:false});
                                                }
                                            }else{
                                                if(balance < text){
                                                    if(!disable){
                                                        this.refs.toast.show('输入金额超过账户余额',1000);
                                                        this.setState({disable:true,pay_count:text});
                                                    }
                                                }else{
                                                    this.setState({pay_count:text, disable:false});
                                                }
                                            }
                                        }}
                                        placeholderTextColor={'#B5B5B5'}
                                    />
                                </View>
                            </View>
                            <View style={{marginTop:5}}>
                                <Text style={styles.feeText}>提现手续费：<Text style={{color:'#EA5404'}}>{fee.toFixed(2)+'元'}</Text>，实际到账：<Text style={{color:'#EA5404'}}>{this.state.pay_count-fee<0?'0.00':(this.state.pay_count-fee).toFixed(2)}元</Text></Text>
                                {session.user.isShop == 1  || session.user.productKey == "LiXiaoShuang" ? null : <Text style={styles.feeText}>每月首笔提现免手续费</Text>}
                                
                            </View>

                            <View style={[styles.submitBtnContainer,{marginTop:20},disable?{backgroundColor:'#DEDEDE'}:{}]}>
                                <Touch onPress={disable?null:(session.user && session.user.withdraw_password ? this._showPwdDialog.bind(this) : this._showPwdSetDialog.bind(this))} style={styles.submitBtn}>
                                    <Text style={[styles.submitBtnText,disable?{color:'#f5f5f5'}:{}]}>提现</Text>
                                </Touch>
                            </View>
                        </View>
                  </SimpleDialog>
                  <ToastTip ref="toast" offsetY={Wheight - 64 - 315}/>
                  <LoadingTip show={this.state.loadingShow}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
MyMoney = connectHelper(state => state)(MyMoney);

module.exports = MyMoney;
